﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CheckTouch : MonoBehaviour
{
    public static CheckTouch Instance { get; private set; }

    public Slider slider;
    public Action action;
    bool isGet = false;
    bool isAd = false;
    public GameObject boxBg;
    public GameObject box;
    private float origin;
    private float form;
    private float to;
    private float posY;
    int touchID = -1;

    public static void Show(Action action = null)
    {
        if (!Instance)
        {
            GameObject prefab = Resources.Load("Prefab/UIPrefab/ChestTouch") as GameObject;
            GameObject obj = Instantiate(prefab);
            Instance = obj.GetComponent<CheckTouch>();
        }
        Instance.action = action;
        Instance.slider.value = 0;
        Instance.isGet = false;
        Instance.isAd = false;
        Instance.gameObject.SetActive(true);
    }

    // Start is called before the first frame update
    void Start()
    {
        Instance = this;
        DontDestroyOnLoad(gameObject);
        origin = box.transform.localPosition.y;
        form = origin * 1.3f;
        to = origin * 0.7f;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        var speed = 1 * 0.015f;
        slider.value -= Time.fixedDeltaTime / 3;
        boxBg.transform.Rotate(Vector3.back * 10 * speed);
        Vector3 pos = box.transform.localPosition;

        posY += speed;
        pos.y = Mathf.Lerp(form, to, posY);
        if (posY >= 1)
        {
            posY = 0;
            var temp = form;
            form = to;
            to = temp;
        }
        box.transform.localPosition = pos;
    }

    public void TouchCheck()
    {
        slider.value += 0.1f;
    }

    public void CheckValue()
    {
        if (slider.value >= 0.2f && !isAd)
        {
            isAd = true;
            if (!AdManager.Instance.ShieldAddress) AdManager.Instance.ShowNative();
        }
        if (slider.value >= 0.6f && !isGet)
        {
            isGet = true;
            //黑包视频
            if (!AdManager.Instance.ShieldAddress) AdManager.Instance.ShowVideo(null);
            Invoke("invoke", 1);
        }
    }

    private void invoke()
    {
        action?.Invoke();
        gameObject.SetActive(false);
    }
}
